package towa.com.remoteWMP;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SettingsDataSource {
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	
	public SettingsDataSource(Context context){
		dbHelper = new MySQLiteHelper(context);
	}
	
	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}
	
	public void close() {
		dbHelper.close();
	}
	
	public long createHost(Host host){
		ContentValues values = new ContentValues();
		values.put("name", host.getName());
		values.put("ip", host.getIp());
		values.put("port", host.getPort());
		return database.insert("hosts", null, values);
	}
	
	public Host getHost(long id){
		Cursor cursor = database.query("hosts", null, "_id = " + id, null, null, null, null);
		if(cursor.moveToFirst())
			return cursorToHost(cursor);
		return null;
	}
	
	public void updateHost(Host host){
		ContentValues values = new ContentValues();
		values.put("name", host.getName());
		values.put("ip", host.getIp());
		values.put("port", host.getPort());
		database.update("hosts", values, "_id = " + host.getId(), null);
	}
	
	public void deleteHost(Host host){
		database.delete("hosts", "_id = " + host.getId(), null);
	}
	
	public List<Host> getAllHosts(){
		List<Host> hosts = new ArrayList<Host>();
		Cursor cursor = database.query("hosts", null, null, null, null, null, null);
		cursor.moveToFirst();
		while(!cursor.isAfterLast()){
			hosts.add(cursorToHost(cursor));
			cursor.moveToNext();
		}
		cursor.close();
		return hosts;
	}
	
	private Host cursorToHost(Cursor cursor){
		Host host = new Host();
		host.setId(cursor.getLong(0));
		host.setName(cursor.getString(1));
		host.setIp(cursor.getString(2));
		host.setPort(cursor.getInt(3));
		return host;
	}
	
	public class MySQLiteHelper extends SQLiteOpenHelper {

		public MySQLiteHelper(Context context) {
			super(context, "WMPRemote.db", null, 1);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("create table hosts (_id integer primary key autoincrement, name text, ip text not null, port integer)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("drop table if exists hosts");
			onCreate(db);
		}
		
	}

}
